package com.mallsystem.orderservice.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mallsystem.common.bean.*;
import com.mallsystem.common.exception.AllException;
import com.mallsystem.common.service.GoodsService;
import com.mallsystem.common.service.OrderService;
import com.mallsystem.common.service.UserAddrService;
import com.mallsystem.common.service.UserService;
import com.mallsystem.orderservice.mapper.CartMapper;
import com.mallsystem.orderservice.mapper.OrderDetailMapper;
import com.mallsystem.orderservice.mapper.OrderMapper;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private CartMapper cartMapper;
    @DubboReference
    private UserAddrService userAddrService;
    @DubboReference
    private GoodsService goodsService;
    @DubboReference
    private UserService userService;

    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public void insert(OrderVo orderVo) throws AllException {
        /*
        1.生成订单
        2.生成详情
        3.删除购物车
         */
        //创建订单对象
        Order order = new Order();
        //生成订单ID - 雪花算法
        String orderId = IdUtil.getSnowflakeNextIdStr();
        //设置订单id
        order.setId(orderId);
        //获取地址对象
        Addr addr = userAddrService.selectById(orderVo.getAddrId());
        //设置地址详情
        order.setAddrDetail(addr.getContact() + " "
                + addr.getPhone() + " "
                + addr.getProvince() + " "
                + addr.getCity() + " "
                + addr.getDistrict() + " "
                + addr.getStreet() + " "
                + addr.getAddress());
        //生成订单
        order.setUserId(orderVo.getUserId());
        order.setAddrId(orderVo.getAddrId());
        order.setStatus(0);
        orderMapper.insert(order);
        //生成详情 每个购物车的id对于一个商品详情
        for (Integer cartId : orderVo.getCartIds()) {
            //获取购物车 - 判断购物车是否合法
            Cart cart = cartMapper.selectById(cartId);
            if(cart == null){
                throw new AllException("购物车不存在，无法生成订单");
            }
            if(!cart.getUserId().equals(orderVo.getUserId())){
                throw new AllException("购物车不合法,无法生成订单");
            }
            Goods goods = goodsService.selectById(cart.getGoodsId());
            if(goods == null){
                throw new AllException("商品不存在，无法生成订单");
            }
            //商品是否下架
            if(goods.getStatus().equals(0)){
                throw new AllException("商品下架，无法生成订单");
            }
            //库存是否充足
            if(goods.getCount() < cart.getCount()){
                throw new AllException("商品库存不足，无法生成订单");
            }
            //减去商品库存
            goods.setCount(goods.getCount() - cart.getCount());
            goodsService.update(goods);
            //添加详情
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setCount(cart.getCount());
            orderDetail.setPrice(goods.getPrice());
            orderDetail.setOrderId(orderId);
            orderDetail.setGoodsId(goods.getId());
            orderDetailMapper.insert(orderDetail);

        }
        //删除购物车
        cartMapper.deleteBatch(Arrays.asList(orderVo.getCartIds()));
        orderVo.setOrderId(orderId);
    }

    @Override
    public boolean update(Order order) throws AllException {
        if(orderMapper.selectById(order.getId()) == null){
            throw new AllException("该订单不存在");
        }
        return orderMapper.update(order) == 1;
    }

    @Override
    public PageInfo<Order> selectByCondition(Order condition, Integer pageNum, Integer pageSize) {
        //设置分页参数
        PageHelper.startPage(pageNum,pageSize);
        //查询
        List<Order> order = orderMapper.selectByCondition(condition);
        for (Order o : order) {
            BigDecimal sum = new BigDecimal(0);
            for (OrderDetail orderDetail : o.getDetailList()) {
                BigDecimal price = orderDetail.getPrice();
                sum = sum.add(price);
                Goods goods = goodsService.selectById1(orderDetail.getGoodsId());
                orderDetail.setGood(goods);
            }
            o.setPrice(sum);
        }
        //order.stream().forEach(item -> item.setUser(userService.selectById(item.getUserId())));
        //创建分页信息
        PageInfo<Order> pageInfo = new PageInfo<>(order);
        return pageInfo;
    }

    @Override
    public Order selectById(String id,Integer userId) throws AllException {
        Order order = orderMapper.selectById(id);
        //判断订单是否属于当前用户
        if(!order.getUserId().equals(userId)){
            throw new AllException("订单不属于当前用户，请联系管理员");
        }

        BigDecimal sum = new BigDecimal(0);
        for (OrderDetail orderDetail : order.getDetailList()) {
            BigDecimal price = orderDetail.getPrice();
            sum = sum.add(price);
            Goods goods = goodsService.selectById1(orderDetail.getGoodsId());
            orderDetail.setGood(goods);
        }
        order.setPrice(sum);
        return order;
    }
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public void pay(OrderVo orderVo) throws AllException {
        Order order = orderMapper.selectById(orderVo.getOrderId());
        //判断订单是否存在
        if(order == null){
            throw new AllException("订单不存在，无法支付");
        }
        //判断订单是否属于当前用户
        if(!order.getUserId().equals(orderVo.getUserId())){
            throw new AllException("订单不属于当前用户，无法支付");
        }
        //判断订单状态是否为未支付
        if(!order.getStatus().equals(0)){
            throw new AllException("订单状态错误，无法支付");
        }
        order.setStatus(1);
        //设置支付方式默认余额支付
        order.setPayType(orderVo.getPayType());
        //生成快递单号
        String expressId = IdUtil.getSnowflakeNextIdStr();
        order.setExpress(expressId);
        //更新订单
        orderMapper.update(order);
        //查询用户
        User user = userService.selectById(orderVo.getUserId());
        //判断支付密码是否存在，是否正确
        String payPwdMySQL = user.getPayPassword();
        if(payPwdMySQL == null){
            throw new AllException("未设置支付密码，请设置后再重试");
        }
        //对用户输入支付密码进行加密
        String  md5Pwd = SecureUtil.md5(SecureUtil.md5(orderVo.getPayPwd() + user.getSalt()));
        if(!md5Pwd.equals(payPwdMySQL)){
            throw new AllException("支付密码错误，无法支付");
        }
        //计算当前订单的总金额
        BigDecimal sum = new BigDecimal(0);
        for (OrderDetail orderDetail : order.getDetailList()) {
            BigDecimal count = new BigDecimal(orderDetail.getCount());
            BigDecimal price = orderDetail.getPrice();
            sum = sum.add(price.multiply(count));
        }
        //判断余额是否充足 比较器
        if(user.getMoney().compareTo(sum) < 0){
            throw new AllException("余额不足，无法支付");
        }
        //扣除余额
        User u = new User();
        u.setId(user.getId());
        u.setMoney(user.getMoney().subtract(sum));
        userService.update(u);
    }

    @Override
    public Order selectByIdOnAdmin(String id) throws AllException {
        Order order = orderMapper.selectById(id);
        if(order == null){
            throw new AllException("订单不存在");
        }
        return order;
    }
}
